package com.project.common.datasource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: Breet
 * @Date: 2018/6/5 15:52
 * @Description:
 */
@Aspect
@Component
public class DynamicDataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    /**
     * 动态切换切面
     */
    @Pointcut("execution( * com.project.biz.*.*(..))")
    public void daoAspect() {
    }

    /**
     * 面向切面动态切换数据源
     * @param point
     */
    @Before("daoAspect()")
    public void switchDataSource(JoinPoint point) {
        Boolean isQueryMethod = isQueryMethod(point.getSignature().getName());
        if (isQueryMethod) {
            DynamicDataSourceContextHolder.useSlaveDataSource();
        }else{
            DynamicDataSourceContextHolder.useMasterDataSource();
        }
        logger.info("Switch DataSource to [{}] in Method [{}]", DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature());
    }

    @After("daoAspect())")
    public void restoreDataSource(JoinPoint point) {
        DynamicDataSourceContextHolder.clearDataSourceKey();
        DynamicDataSourceContextHolder.useMasterDataSource();
    }

    /**
     * 判断调用的方法是读还是写
     * @param methodName
     * @return false:写,true:读
     */
    private Boolean isQueryMethod(String methodName) {
        if(methodName.startsWith("get")
                || methodName.startsWith("select")
                || methodName.startsWith("check")
                || methodName.startsWith("find")){
            return  true;
        }
        return false;
    }
}
